package com.tom.happy.mrs.chicken;


import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.baidu.mobads.AppActivity;
import com.baidu.mobads.BaiduManager;
import com.orhanobut.logger.Logger;
import com.tom.happy.mrs.chicken.service.MusicService;
import com.tom.happy.mrs.chicken.utils.PrefUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.tom.happy.mrs.chicken.BaseFragment.GAME_TYPE_COOP_TWO;

public class MainActivity extends Activity implements View.OnClickListener {
    private Context mContext;
    private Intent mServiceIntent;

    private static final String PREFS_SHOW_COOP_TIP = "showCoopTip";
    private static final String PREFS_SHOW_LAY_EGGS_TIP = "showLayEggsTip";
    private Fragment mLayEggsFragment;
    private Fragment mCoopFragment;
    private Fragment mCurrentFragment;

    // 1-单房子抓小鸡; 2-单房子抓小鸡计时; 3-双房子; 4-双房子计时
    // 0-小鸡下蛋游戏.
    protected int mGameType;

    private AdView mBaiduAdView;
    private ViewGroup mContentView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        fullscreen();
        mContext = this;
        mContentView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        setContentView(mContentView);
        PushAgent.getInstance(this).onAppStart();

        ImageButton quitView = (ImageButton) findViewById(R.id.quit);
        ((AnimationDrawable) quitView.getBackground()).start();
        quitView.setOnClickListener(this);

        findViewById(R.id.lay_egg).setOnClickListener(this);
        findViewById(R.id.chicken_coop).setOnClickListener(this);
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-21");
            if (System.currentTimeMillis() >= date.getTime()) {
                addBaiduAd();
            }
        } catch (ParseException e) {
        }
    }

    private void fullscreen() {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
    @Override
    public void onBackPressed() {
        showConformDialog();
    }

    public void processBackPressed() {
        if (mCurrentFragment != null) {
            getFragmentManager().beginTransaction().remove(mCurrentFragment).commit();
            mCurrentFragment = null;
            findViewById(R.id.main_layout).setVisibility(View.VISIBLE);
            startService(mServiceIntent);
        } else {
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopService(mServiceIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mCurrentFragment == null) {
            mServiceIntent = new Intent(mContext, MusicService.class);
            startService(mServiceIntent);
        }
    }

    @Override
    protected void onDestroy() {
        if (mBaiduAdView != null) {
            mBaiduAdView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        MobclickAgent.onResume(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.quit:
                showConformDialog();
                break;
            case R.id.lay_egg:
                if (getSharedPreferences(BaseFragment.PREFS_NAME, Context.MODE_PRIVATE).getBoolean(PREFS_SHOW_LAY_EGGS_TIP, true)) {
                    showTips(0);
                } else {
                    startLayEggsGame();
                }
                break;
            case R.id.chicken_coop:
                if (getSharedPreferences(BaseFragment.PREFS_NAME, Context.MODE_PRIVATE).getBoolean(PREFS_SHOW_COOP_TIP, true)) {
                    showTips(1);
                } else {
                    startCoopGame();
                }
                break;
        }
    }

    public void showConformDialog() {
        final Dialog dialog = new Dialog(mContext, R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.confirm_dialog);
        dialog.findViewById(R.id.confirm_quit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                fullscreen();
                processBackPressed();
            }
        });
        dialog.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                fullscreen();
            }
        });

        dialog.show();
    }

    private void showTips(final int type) {
        final Dialog dialog = new Dialog(mContext, R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.tips_dialog);
        ImageButton quitView = (ImageButton) dialog.findViewById(com.tom.happy.mrs.chicken.R.id.quit);
        ((AnimationDrawable) quitView.getBackground()).start();
        ImageView guideImage = ((ImageView) dialog.findViewById(R.id.guide_image));
        guideImage.setBackgroundResource(type == 0 ? R.drawable.guide_happy_mrs_chicken : R.drawable.guide_chicken_coop);
        ImageView iv = (ImageView) dialog.findViewById(R.id.play);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences(BaseFragment.PREFS_NAME, Context.MODE_PRIVATE)
                        .edit();
                switch (type) {
                    case 0:
                        editor.putBoolean(PREFS_SHOW_LAY_EGGS_TIP, false).commit();
                        startLayEggsGame();
                        break;
                    case 1:
                        editor.putBoolean(PREFS_SHOW_COOP_TIP, false).commit();
                        startCoopGame();
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.findViewById(R.id.quit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    private void startLayEggsGame() {
        mLayEggsFragment = new LayEggsFragment();
        addFragment(mLayEggsFragment);
        stopService(mServiceIntent);
    }

    private void startCoopGame() {
        mCoopFragment = new ChickenCoopFragment();
        mGameType = GAME_TYPE_COOP_TWO;
        addFragment(mCoopFragment);
        stopService(mServiceIntent);
    }

    private void addFragment(Fragment fragment) {
        findViewById(R.id.main_layout).setVisibility(View.GONE);
        // 开启Fragment事务
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_container, fragment);
        // 事务提交
        transaction.commit();

        mCurrentFragment = fragment;
    }

    private void addBaiduAd() {
        BaiduManager.init(this);

        AppActivity.setActionBarColorTheme(AppActivity.ActionBarColorTheme.ACTION_BAR_RED_THEME);

        if (!PrefUtils.showAd(this)) {
            return;
        }
        // 创建广告View
        String adPlaceId = PrefUtils.getBannerAdID(this); //  重要：请填上您的广告位ID，代码位错误会导致无法请求到广告
        mBaiduAdView = new AdView(this, adPlaceId);
        // 设置监听器
        mBaiduAdView.setListener(new AdViewListener() {
            public void onAdSwitch() {
                Log.d("12345", "onAdSwitch");
            }

            public void onAdShow(JSONObject info) {
                // 广告已经渲染出来
                Logger.i("onAdShow " + info.toString() + ",height: " + mBaiduAdView.getHeight());
            }

            public void onAdReady(AdView mBaiduAdView) {
                // 资源已经缓存完毕，还没有渲染出来
                Logger.i("onAdReady " + mBaiduAdView);
            }

            public void onAdFailed(String reason) {
                Logger.i("onAdFailed " + reason);
            }

            public void onAdClick(JSONObject info) {
                Logger.i("onAdClick " + info.toString());
            }

            @Override
            public void onAdClose(JSONObject arg0) {
                Log.d("12345", "onAdClose");
            }
        });
        RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rllp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rllp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mContentView.addView(mBaiduAdView, rllp);
    }

}
